package com.umeox.moto.mqtt;

import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTools {
    private static final String TAG = "ThreadTools";
    private static LoopHandler uiThreadHandler = new LoopHandler(Looper.getMainLooper());
    private static ExecutorService executorService = null;

    public ThreadTools() {
    }

    public static void runOnUiThread(Runnable runnable) {
        if (runnable != null) {
            uiThreadHandler.enqueue(runnable);
        }
    }

    public static String getProcessName(Context context, int pid) {
        String ret = null;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (null != am) {
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps != null) {
                Iterator var5 = runningApps.iterator();

                while (var5.hasNext()) {
                    ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) var5.next();
                    if (info.pid == pid) {
                        ret = info.processName;
                        break;
                    }
                }
            }
        }

        return ret;
    }

    public static boolean isAppBroughtToBackgroundByTask(Application app) {
        boolean ret = false;

        try {
            ActivityManager activityManager = (ActivityManager) app.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = ((ActivityManager.RunningTaskInfo) tasks.get(0)).topActivity;
                String packageName = app.getPackageName();
                ret = !topActivity.getPackageName().equals(packageName);
            }

            return ret;
        } catch (Exception var6) {
            return true;
        }
    }

    public static void submitTask(Runnable r, boolean isRunOnUIThread) {
        submitTask(r, isRunOnUIThread, 0);
    }

    public static void submitTask(Runnable r, boolean isRunOnUIThread, int delayInMillion) {
        if (isRunOnUIThread) {
            getUIThreadHandler().enqueue(r, delayInMillion);
        } else {
            getExecutorService().submit(r);
        }

    }

    private static ExecutorService getExecutorService() {
        if (null == executorService) {
            createThreadPool();
        }

        return executorService;
    }

    private static LoopHandler getUIThreadHandler() {
        if (uiThreadHandler == null) {
            uiThreadHandler = new LoopHandler(Looper.myLooper());
        }

        return uiThreadHandler;
    }

    private static void createThreadPool() {
        int core = Runtime.getRuntime().availableProcessors();
        if (core > 10) {
            executorService = new ThreadPoolExecutor(core,
                    core + 7,
                    60L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue(15),
                    new ALXHDefaultThreadFactory(),
                    new ThreadPoolExecutor.DiscardPolicy());
        } else {
            executorService = new ThreadPoolExecutor(core,
                    15,
                    60L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue(15),
                    new ALXHDefaultThreadFactory(),
                    new ThreadPoolExecutor.DiscardPolicy());
        }

    }

    private static class ALXHDefaultThreadFactory implements ThreadFactory {
        private final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        ALXHDefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
            this.namePrefix = "pool-" + this.poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }

            Process.setThreadPriority(10);
            return t;
        }
    }

    public static final class LoopHandler extends Handler {
        private static final String TAG = "ThreadTools_ThreadTools";

        public LoopHandler(Looper looper) {
            super(looper);
        }

        public void enqueue(Runnable runnable) {
            this.enqueue(runnable, 0);
        }

        public void enqueue(Runnable runnable, int delay) {
            Message message = this.obtainMessage();
            message.obj = runnable;
            this.sendMessageDelayed(message, (long) delay);
        }

        @Override
        public void handleMessage(Message msg) {
            if (null != msg && msg.obj instanceof Runnable) {
                try {
                    ((Runnable) msg.obj).run();
                } catch (Exception e) {
                    if (BuildConfig.DEBUG) {
                        Log.e(TAG, "run task error: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
